package com.qf.util;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.rmi.server.UID;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/21/19:47
 * @Description: 订单id 时间+随机数(5位)+用户id后四位+流水号
 */
@Component
public class OrderUtil {
    @Autowired
    private  StringRedisTemplate redisTemplate;
   public  String createOid(Integer uid){
       StringBuffer buffer = new StringBuffer();
       //时间
       String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
       //随机数

       String random = RandomStringUtils.random(5, false, true);
       //用户id后四位
       String idStr=lasteUserId(uid);
     //流水号
       Long aLong = redisTemplate.opsForValue().increment("order-index");

       return  buffer.append(date).append(random).append(idStr).append(aLong).toString();
   }
   public  String lasteUserId(Integer id){
       StringBuffer buffer = new StringBuffer();
       String s = id.toString();
       buffer.append(id);
       if (s.length()<4){
           for (int i=0; i<4-s.length();i++){
               buffer.insert(0,"0");
           }

       } else {
           buffer.append(s.length() - 4);
       }
       return buffer.toString();
   }
}
